package com.heart.sell.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * cookie 工具类
 *
 * @author Luo Zhen
 * @create 2019-04-30 16:36
 */
public class CookieUtil {


    public static void set(HttpServletResponse response,
                           String name,
                           String value,
                           int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 返回cookie
     *
     * @param request
     * @param name
     * @return
     */
    public static Cookie get(HttpServletRequest request,
                             String name) {
        Map<String, Cookie> cookMap = readCookMap(request);
        if (cookMap.containsKey(name)) {
            return cookMap.get(name);
        } else {
            return null;
        }
    }

    /**
     * 将cookie封装成map
     *
     * @param request
     * @return
     */
    private static Map<String, Cookie> readCookMap(HttpServletRequest request) {
        Map<String, Cookie> cookMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                cookMap.put(cookie.getName(), cookie);
            }
        }
        return cookMap;
    }

}
